#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<unistd.h>
#include<sys/un.h>

#define MAXLINE 4096

int main(int argc, char** argv){
    int  listenfd, connfd;
    struct sockaddr_un  servaddr;
    char  buff[4096];
    int  n;

    if( (listenfd = socket(AF_UNIX, SOCK_SEQPACKET, 0)) == -1 ){
        printf("create socket error: %s(errno: %d)\n",strerror(errno),errno);
        return 0;
    }

    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sun_family = AF_UNIX;
    memcpy(servaddr.sun_path, "/tmp/uds-tcp.sock",strlen("/tmp/uds-tcp.sock"));

    if( bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1){
        printf("bind socket error: %s(errno: %d)\n",strerror(errno),errno);
        return 0;
    }

    if( listen(listenfd, 10) == -1){
        printf("listen socket error: %s(errno: %d)\n",strerror(errno),errno);
        return 0;
    }

    printf("======waiting for client's request======\n");
    bool close_signal = false;
    while(1){
        if( (connfd = accept(listenfd, (struct sockaddr*)nullptr, nullptr)) == -1){
            printf("accept socket error: %s(errno: %d)",strerror(errno),errno);
            continue;
        }
        while (1) {
            memset(buff, 0, MAXLINE);
            n = recv(connfd, buff, MAXLINE, 0);
            if(n<=0)
                break;
            printf("recv msg from client: %s\n", buff);
            if(strcmp(buff,"exit")==0){
                send(connfd, "exit", strlen("exit"), 0);
                break;
            }else{
                if(strcmp(buff, "close")==0){
                    close_signal=true;
                    send(connfd, "exit", strlen("exit"), 0);
                    break;
                }
                send(connfd, "ok!", strlen("ok!"), 0);
            }
        }

        close(connfd);
        if(close_signal){
            break;
        }
    }
    close(listenfd);
    return 0;
}
